package com.yyn.seckill.rabbitmq;

import com.yyn.seckill.config.exceptionhandler.CustomException;
import com.yyn.seckill.entity.Order;
import com.yyn.seckill.entity.dto.GoodDetialListDto;
import com.yyn.seckill.entity.dto.SeckillMessage;
import com.yyn.seckill.service.GoodsService;
import com.yyn.seckill.service.OrderService;
import com.yyn.seckill.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Slf4j
@Service
public class SeckillReceiver {
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message){
        log.info("接收到的信息："+message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodId = seckillMessage.getGoodId();
        Long userId = seckillMessage.getUserId();
        GoodDetialListDto goodDetialListDto = goodsService.goodDetialList(String.valueOf(goodId));
        if(goodDetialListDto.getStockCount()<1){
            throw new CustomException(20001,"库存已无");
        }
        //            检查是否重复购买
        Order orderCheck = (Order) redisTemplate.opsForValue().get("orderId=userId:" + userId + "goodId:" + goodId);
        if (!StringUtils.isEmpty(orderCheck)) {
            throw new CustomException(20001, "已抢购 不能重复抢");
        }
//        下订单
        Order order = orderService.getOrder(userId, goodId);

    }
}
